<template>
  <div class="wrap-item">
    <!-- 搜索-->
    <el-form ref="formSearch" :model="formSearch" size="small" inline>
      <el-form-item>
        <el-input
          v-model.trim="formSearch.param.roleName"
          placeholder="请输入角色名称"
          maxlength="20"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-select
          clearable
          v-model="formSearch.param.status"
          placeholder="请选择状态"
        >
          <el-option label="启用" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <span class="wrap-btn wrap-primary" @click="search">查询</span>
        <span
          class="wrap-btn wrap-success"
          v-if="$checkPermission(101)"
          @click="add"
          >添加角色</span
        >
        <span
          class="wrap-btn wrap-warning"
          @click="download"
          v-if="$checkPermission(108)"
          >导出</span
        >
      </el-form-item>
    </el-form>
    <!-- 数据列表 -->
    <div class="wrap-item-roll">
      <el-table
        :data="tableData"
        :header-cell-style="{ background: '#F6F7F9' }"
      >
        <el-table-column
          type="index"
          width="50"
          label="序号"
          align="center"
        ></el-table-column>
        <el-table-column prop="roleName" label="角色名称"></el-table-column>
        <el-table-column prop="roleDesc" label="角色描述">
          <template slot-scope="scope">
            <el-tooltip
              popper-class="ellipsis-tip"
              :content="scope.row.roleDesc"
              placement="top-start"
            >
              <span class="ellipsis">{{ scope.row.roleDesc }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="addName" label="创建人"></el-table-column>
        <el-table-column prop="addTime" label="创建时间"></el-table-column>
        <el-table-column label="状态" width="80px" align="center">
          <template slot-scope="scope">
            <el-link
              type="success"
              :underline="false"
              v-if="scope.row.status == 0"
              >启用</el-link
            >
            <el-link
              type="danger"
              :underline="false"
              v-if="scope.row.status == 1"
              >停用</el-link
            >
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="操作"
          width="80px"
          align="center"
        >
          <template slot-scope="scope">
            <el-dropdown @command="(command) => handle(command, scope.row)">
              <span class="el-dropdown-link">
                更多
                <i class="el-icon-arrow-down el-icon--right"></i>
              </span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="view" v-if="$checkPermission(104)"
                  >查看</el-dropdown-item
                >
                <el-dropdown-item command="edit" v-if="$checkPermission(102)"
                  >编辑</el-dropdown-item
                >
                <el-dropdown-item
                  command="changeStatus"
                  v-if="scope.row.status == 1 && $checkPermission(105)"
                  >启用</el-dropdown-item
                >
                <el-dropdown-item
                  command="changeStatus"
                  v-if="scope.row.status == 0 && $checkPermission(106)"
                  >停用</el-dropdown-item
                >
                <el-dropdown-item command="remove" v-if="$checkPermission(103)"
                  >删除</el-dropdown-item
                >
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <web-page
      :page="formSearch.pageNum"
      :size="formSearch.pageSize"
      :total="total"
      @sizeChange="sizeChange"
      @currentChange="currentChange"
    ></web-page>
    <!-- 对话框 -->
    <el-drawer :title="title" :wrapperClosable="false" :visible.sync="visible">
      <el-form label-width="110px" :model="form" size="medium">
        <el-form-item label="角色名称" required>
          <el-input
            v-model.trim="form.roleName"
            clearable
            maxlength="20"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色权限" required>
          <role-tree
            ref="tree"
            nodeKey="menuNo"
            parentId="parentNo"
            :data="treeData"
            :defaultProps="{
              label: 'menuName',
              children: 'child',
            }"
          ></role-tree>
        </el-form-item>
        <el-form-item label="子系统管理员">
          <el-select
            v-model="form.adminFlag"
            style="width: 100%"
            placeholder="请选择是否子系统管理员"
          >
            <el-option label="是" value="0"></el-option>
            <el-option label="否" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input
            type="textarea"
            v-model.trim="form.roleDesc"
            placeholder="请输入角色描述"
            maxlength="100"
            resize="none"
          ></el-input>
        </el-form-item>
        <el-form-item style="text-align: end">
          <span class="wrap-btn wrap-success" @click="save">确定</span>
          <span class="wrap-btn wrap-default" @click="visible = false"
            >取消</span
          >
        </el-form-item>
      </el-form>
    </el-drawer>
    <!-- 查看 -->
    <el-dialog title="查看" :visible.sync="isLook" width="888px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="角色名称">
          {{ lockData.roleName }}
        </el-descriptions-item>
        <el-descriptions-item label="角色状态">
          {{ lockData.status == 0 ? '启用' : '停用' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">
          {{ lockData.addName }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ lockData.addTime }}
        </el-descriptions-item>
        <el-descriptions-item label="角色权限" :span="2">
          <div class="wrap-tree">
            <el-tree
              ref="trees"
              node-key="menuNo"
              :accordion="true"
              :check-strictly="true"
              :default-expand-all="true"
              show-checkbox
              :data="treeData"
              :props="{
                label: 'menuName',
                children: 'child',
              }"
              class="isChoose"
            ></el-tree>
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="是否子系统管理员" :span="2">
          {{ lockData.adminFlag == 0 ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item label="角色描述" :span="2">
          <el-tooltip
            popper-class="ellipsis-tip-span2"
            :content="lockData.roleDesc"
            placement="top-start"
          >
            <span class="ellipsis-span2">{{ lockData.roleDesc }}</span>
          </el-tooltip>
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script>
import roleTree from './role-tree'
export default {
  components: { roleTree },
  data() {
    return {
      treeData: [],
      formSearch: {
        pageNum: 1,
        pageSize: 10,
        param: {},
      },
      total: null,
      tableData: [],
      visible: false,
      title: '添加角色',
      form: {},
      isLook: false,
      lockData: { checkedKeys: [] },
    }
  },
  created() {
    this.menuList()
    this.itemList()
  },
  methods: {
    itemList() {
      // 获取列表
      this.$axios.post('/admin/role/page', this.formSearch).then((data) => {
        this.tableData = []
        if (data.code == 200) {
          this.tableData = data.data.list
          this.total = data.data.total
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    sizeChange(val) {
      //每页条数
      this.formSearch.pageSize = val
      this.itemList()
    },
    currentChange(val) {
      //分页
      this.formSearch.pageNum = val
      this.itemList()
    },
    search() {
      //搜索
      this.formSearch.pageNum = 1
      this.itemList()
    },
    add() {
      //添加
      this.form = { status: '0' }
      this.title = '添加角色'
      this.visible = true
      this.$nextTick(function () {
        this.$refs.tree.$refs.tree.setCheckedKeys([])
      })
    },
    handle(command, row) {
      //操作
      if (!command) {
        this.$message.error('菜单选项缺少command属性')
        return
      }
      switch (command) {
        case 'view':
          this.$axios.get('/admin/role/find?id=' + row.id).then((data) => {
            this.lockData = { checkedKeys: [] }
            if (data.code == 200) {
              this.lockData = data.data
              let arr = []
              data.data.menuNo.forEach((element) => {
                arr.push(element.menuNo)
                if (element.buttons.length > 0) {
                  arr = [...arr, ...element.buttons]
                }
              })
              this.$nextTick(function () {
                this.$refs.trees.setCheckedKeys(arr)
              })
              this.isLook = true
            } else {
              this.$message.error(data.msg)
            }
          })
          break
        case 'edit':
          this.title = '编辑角色'
          this.$axios.get('/admin/role/find?id=' + row.id).then((data) => {
            this.form = { status: '0' }
            if (data.code == 200) {
              this.form = data.data
              this.form.adminFlag = String(data.data.adminFlag)
              this.visible = true
              let arr = []
              data.data.menuNo.forEach((element) => {
                arr.push(element.menuNo)
                if (element.buttons.length > 0) {
                  arr = [...arr, ...element.buttons]
                }
              })
              this.$nextTick(function () {
                this.$refs.tree.$refs.tree.setCheckedKeys(arr)
              })
            } else {
              this.$message.error(data.msg)
            }
          })
          break
        case 'changeStatus':
          //启用停用
          const status = row.status == 0 ? 1 : 0
          this.$axios
            .get('/admin/role/start?id=' + row.id + '&status=' + status)
            .then((data) => {
              if (data.code == 200) {
                this.itemList()
                this.$message.success('操作成功！')
              } else {
                this.$message.error(data.msg)
              }
            })
          break
        case 'remove':
          //删除
          this.$confirm('您确定要删除该条数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.$axios.get('/admin/role/del?id=' + row.id).then((data) => {
                if (data.code == 200) {
                  this.itemList()
                  this.$message.success('操作成功！')
                } else {
                  this.$message.error(data.msg)
                }
              })
            })
            .catch(() => {})
          break
      }
    },
    save() {
      //保存
      if (!this.form.roleName) {
        this.$message.error('请输入角色名称')
        return
      }
      const menus = this.$refs.tree.$refs.tree.getCheckedNodes()
      if (menus.length == 0) {
        this.$message.error('请选择角色权限')
        return
      }
      const arr = []
      menus.forEach((element) => {
        if (element.level == 100) {
          if (arr.length == 0) {
            arr.push({ buttons: [element.menuNo], menuNo: element.parentNo })
          } else {
            if (arr.some((citem) => citem.menuNo == element.parentNo)) {
              arr.forEach((item, index) => {
                if (item.menuNo == element.parentNo) {
                  arr[index].buttons.push(element.menuNo)
                }
              })
            } else {
              arr.push({
                buttons: [element.menuNo],
                menuNo: element.parentNo,
              })
            }
          }
        } else {
          arr.push({
            buttons: [],
            menuNo: element.menuNo,
          })
        }
      })
      this.form.menuNo = arr
      this.$axios.post('/admin/role/edit', this.form).then((data) => {
        if (data.code == 200) {
          this.visible = false
          this.$message.success('操作成功！')
          this.itemList()
        } else {
          this.$message.error(data.msg)
        }
      })
    },
    download() {
      //导出
      this.$axios
        .post('/admin/role/export', this.formSearch, { responseType: 'blob' })
        .then((data) => {
          const reader = new FileReader()
          reader.readAsDataURL(data)
          reader.onload = function (e) {
            const a = document.createElement('a')
            a.download = '角色列表'
            a.href = e.target.result
            a.click()
          }
        })
    },
    menuList() {
      // 获取菜单数据
      this.$axios.get('/admin/menu/listMenus').then((data) => {
        this.treeData = []
        if (data.code == 200) {
          this.treeData = data.data
        } else {
          this.$message.error(data.msg)
        }
      })
    },
  },
}
</script>
<style scoped>
.wrap-tree {
  max-height: 300px;
  overflow-y: scroll;
}
.wrap-tree::-webkit-scrollbar {
  height: 0;
}
.isChoose {
  pointer-events: none;
}
</style>
